package hn.cch.servlet.servlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@WebServlet(urlPatterns = "/web/async", asyncSupported = true)
public class AsyncServlet extends HttpServlet {

    private static final Logger logger = LoggerFactory.getLogger(AsyncServlet.class);

    private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 4, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<>(5));


    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 异步上下文
        final AsyncContext asyncContext = req.startAsync();
        asyncContext.start(() -> {
            new ServletUtils().asyncRun(resp, asyncContext);
        });


        // 线程池
        executor.execute(() -> {
            new ServletUtils().asyncRun(resp, asyncContext);
        });

        // 异步事件监听器
        asyncContext.addListener(new AsyncListener() {
            @Override
            public void onComplete(AsyncEvent asyncEvent) throws IOException {
                logger.info("onComplete");

            }

            @Override
            public void onTimeout(AsyncEvent asyncEvent) throws IOException {
                logger.info("onTimeout");

            }

            @Override
            public void onError(AsyncEvent asyncEvent) throws IOException {
                logger.info("onTimeout");

            }

            @Override
            public void onStartAsync(AsyncEvent asyncEvent) throws IOException {
                logger.info("onStartAsync");

            }
        });


        logger.info("service");
    }
}
